package cloud.xiangyixiang.www.spring.boot.java.basics.controller;

import cloud.xiangyixiang.www.spring.boot.java.basics.classes.PersonSupplier;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * <p>
 * JAVA Supplier
 * </p>
 *
 * @author zhixinglu
 * @date 2023/9/18 15:57
 */
public class SupplierController {

    private int age;

    SupplierController(){
        System.out.println("构造函数,age," + age);
    }

    public static void test(){
        System.out.println("Java8新特性，Supplier");
    }

    private static int getMax(Supplier<Integer> supplier) {
        return supplier.get();
    }

    public static void main(String[] args) {
        // 创建Supplier容器，声明为TestSupplier类型，此时并不会调用对象的构造方法，即不会创建对象
        Supplier<SupplierController> sup = SupplierController::new;
        sup.get().test();
        System.out.println("--------");
        //调用get()方法，此时会调用对象的构造方法，即获得到真正对象
        sup.get();
        //每次get都会调用构造方法，即获取的对象不同
        System.out.println("是否是相同的对象实例"+sup.get()==sup.get().toString());

        System.out.println();

        test1();

        test2();
    }

    /**
     * 获取最大值
     */
    private static void test1() {
        System.out.println("获取最大值:===========");
        Integer[] arr = {10,2,5,3,9,4};
        int max2 = getMax(() -> {
            int max = 0;
            for(Integer i : arr) {
                if(i > max) {
                    max = i;
                }
            }
            return max;
        });
        System.out.println(max2);//10

        System.out.println();
    }

    /**
     * lambda表达式与Supplier的组合使用
     */
    private static void test2(){
        System.out.println("lambda表达式与Supplier的组合使用:===============");
        List<PersonSupplier> list = new ArrayList();
        list.add(new PersonSupplier(1, "guor"));
        list.add(new PersonSupplier(2, "xiaoxia"));
        list.add(new PersonSupplier(3, "xiaotong"));
        Map<Integer, String> map = list.stream().collect(Collectors.toMap(PersonSupplier::getId, PersonSupplier::getName));
        System.out.println(map);
        System.out.println();
    }

}
